<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="计算机网络,HTML5,WebSocket," />










<meta name="description" content="HTML5 WebSocket概述作为新一代的web标准，HTML5为我们提供了很多有用的东西，比如canvas，本地存储（已经分离出去了），多媒体编程接口，当然还有我们的WebSocket。WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯（full-duplex）的网络技术，可以传输基于信息的文本和二进制的数据。它于2011年被IETF定为标准 RFC 6455，同时W">
<meta name="keywords" content="计算机网络,HTML5,WebSocket">
<meta property="og:type" content="article">
<meta property="og:title" content="从HTML5 WebSocket到Socket.io">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/11/从HTML5 WebSocket到Socket.io/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="HTML5 WebSocket概述作为新一代的web标准，HTML5为我们提供了很多有用的东西，比如canvas，本地存储（已经分离出去了），多媒体编程接口，当然还有我们的WebSocket。WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯（full-duplex）的网络技术，可以传输基于信息的文本和二进制的数据。它于2011年被IETF定为标准 RFC 6455，同时W">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/11/1634ea2e300a0c6f?w=504&h=360&f=jpeg&s=17994">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/11/1634ea2e0ed4878d?w=374&h=133&f=jpeg&s=9144">
<meta property="og:updated_time" content="2018-07-15T04:18:43.823Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从HTML5 WebSocket到Socket.io">
<meta name="twitter:description" content="HTML5 WebSocket概述作为新一代的web标准，HTML5为我们提供了很多有用的东西，比如canvas，本地存储（已经分离出去了），多媒体编程接口，当然还有我们的WebSocket。WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯（full-duplex）的网络技术，可以传输基于信息的文本和二进制的数据。它于2011年被IETF定为标准 RFC 6455，同时W">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/5/11/1634ea2e300a0c6f?w=504&h=360&f=jpeg&s=17994">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/11/从HTML5 WebSocket到Socket.io/"/>





  <title>从HTML5 WebSocket到Socket.io | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/11/从HTML5 WebSocket到Socket.io/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">从HTML5 WebSocket到Socket.io</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-11T18:29:36+08:00">
                2018-05-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/计算机网络/" itemprop="url" rel="index">
                    <span itemprop="name">计算机网络</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,141
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="HTML5-WebSocket概述"><a href="#HTML5-WebSocket概述" class="headerlink" title="HTML5 WebSocket概述"></a>HTML5 WebSocket概述</h2><p>作为新一代的web标准，HTML5为我们提供了很多有用的东西，比如canvas，本地存储（已经分离出去了），多媒体编程接口，当然还有我们的WebSocket。WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯（full-duplex）的网络技术，可以传输基于信息的文本和二进制的数据。它于2011年被IETF定为标准 RFC 6455，同时WebSocket API也被W3C定为标准。</p>
<h2 id="一、WebSocket产生的背景"><a href="#一、WebSocket产生的背景" class="headerlink" title="一、WebSocket产生的背景"></a>一、WebSocket产生的背景</h2><h3 id="1-黎明前的黑暗——实时web应用的需求"><a href="#1-黎明前的黑暗——实时web应用的需求" class="headerlink" title="1.黎明前的黑暗——实时web应用的需求"></a>1.黎明前的黑暗——实时web应用的需求</h3><p>web应用的信息交互过程我想大家或多或少都知道一些，通常是客户端通过浏览器发出一个请求，然后服务器端在接受和审核请求后,进行处理并将结果返回给客户端，最后由客户端的浏览器将信息呈现出来。这种通信机制在信息交互不是特别频繁的情况下并没有太大的问题，但对于那些实时性要求高、海量数据并发的应用来说，就显得捉襟见肘了，比如现在常见的网页游戏，证券网站，RSS订阅推送，网页实时对话，打车软件等。通常当客户端准备呈现一些信息时，这些信息在服务器端很有可能就已经过时了。为了满足以上那些场景，大佬们研究出来了一些折衷方案，其中最常用的就是普通轮询和Comet技术，而Comet技术实际上就是轮询的改进，细分起来Comet有两种实现方式：</p>
<ul>
<li>长轮询机制</li>
<li>流技术机制</li>
</ul>
<h4 id="1-1-长轮询机制"><a href="#1-1-长轮询机制" class="headerlink" title="1.1 长轮询机制"></a>1.1 长轮询机制</h4><p>长轮序是对普通轮询的改进和提高。普通轮询简单来说，就是客户端每隔一定的时间就向服务器端发送请求，从而以频繁请求的方式来保持客户端和服务器端的同步。这种同步方案的最大问题是，客户端已固定的频率发送请求时，很可能服务端的数据没有更新，产生很多无用的网络传输，非常低效。</p>
<p>为了减少无效的网络传输，长轮询对普通轮询进行了改进和提高，当服务器端没有数据更新时，链接会保持一段时间的周期，直到数据或状态发生改变或连接时间过期，通过这种机制我们就可以减少很多无效的客户端和服务器间的交互。当然，如果服务器端的数据变更非常频繁的话，这种机制并没有有效的提高性能，和普通轮询没有太大的区别，且长轮询也会耗费更多的资源，比如CPU,内存,带宽等。</p>
<h4 id="1-2-流技术机制"><a href="#1-2-流技术机制" class="headerlink" title="1.2 流技术机制"></a>1.2 流技术机制</h4><p>流技术机制简单来说就是客户端的页面使用一个隐藏的窗口向服务端发出一个长连接的请求。服务器接到请求后作出回应，并不断更新状态，以保证客户端和服务器端的连接不过期。通过这种机制就可以将服务器端的信息不断传向客户端，从而保证信息的时效性。但这种机制对于用户体验并不友好，需要针对不同的浏览器升级不同的方案来改进用户体验，同时这种机制如果在并发情况下发生时，会对服务器的资源造成很大压力。</p>
<h3 id="2-黎明的到来——WebSocket"><a href="#2-黎明的到来——WebSocket" class="headerlink" title="2.黎明的到来——WebSocket"></a>2.黎明的到来——WebSocket</h3><p>正是出于以上几种解决方案都有着各自的局限性,HTML5 WebSocket也就应运而生了，浏览器可以通过JavaScript借助现有的HTTP协议来向服务器发出WebSocket连接的请求，当连接建立后，客户端和服务器端就可以直接通过TCP连接来直接进行数据交换。这是由于websocket协议本质上就是一个TCP连接，所以在数据传输的稳定性和传输量上有所保证，且相对于以往的轮询和Comet技术在性能方面也有了长足的进步：<br><img src="https://user-gold-cdn.xitu.io/2018/5/11/1634ea2e300a0c6f?w=504&amp;h=360&amp;f=jpeg&amp;s=17994" alt="image"></p>
<p>有一点需要注意的是虽然websocket在通信时需要借助HTTP，但它本质上和HTTP有着很大的区别：</p>
<ul>
<li>WebSocket是一种双向通信协议，在建立连接之后，WebSocket服务端和客户端都能主动向对方发送或者接受数据。</li>
<li>WebSocket需要先连接，只有再连接后才能进行相互通信。</li>
</ul>
<p>他们的关系其实就和这张图表现的一样，虽然有相交的部分，但依然有着很大的区别：</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/5/11/1634ea2e0ed4878d?w=374&amp;h=133&amp;f=jpeg&amp;s=9144" alt="image"></p>
<h2 id="二、WebSocket-API的用法"><a href="#二、WebSocket-API的用法" class="headerlink" title="二、WebSocket API的用法"></a>二、WebSocket API的用法</h2><p>由于每个服务器端的语言都有着自己的API，因此首先我们来讨论客户端的API：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个socket实例：</span></span><br><span class="line"><span class="keyword">const</span> socket = <span class="keyword">new</span> WebSocket(ws:<span class="comment">//localhost:9093')</span></span><br><span class="line"><span class="comment">// 打开socket</span></span><br><span class="line">socket.onopen = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 发送一个初始化消息</span></span><br><span class="line">  	socket.send(<span class="string">'Hello Server!'</span>)</span><br><span class="line">  	 <span class="comment">// 服务器有响应数据触发</span></span><br><span class="line">    socket.onmessage = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123; </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'Client received a message'</span>, event)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 出错时触发，并且会关闭连接。这时可以根据错误信息进行按需处理</span></span><br><span class="line">    socket.onerror = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line">  	    <span class="built_in">console</span>.log(<span class="string">'error'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 监听Socket的关闭</span></span><br><span class="line">    socket.onclose = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123; </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'Client notified socket has closed'</span>, event)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 关闭Socket</span></span><br><span class="line">    socket.close(<span class="number">1000</span>, <span class="string">'closing normally'</span>) </span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>是不是感觉HTML5 websocket所提供的API贼鸡儿简单，没错，就是这么简单。但有几点我们需要注意：</p>
<ul>
<li>在创建socket实例的时候，new WebSocket()接受两个参数，第一个参数是ws或wss,第二个参数可以选填自定义协议，如果是多协议，可以是数组的方式。</li>
<li>WebSocket中的send方法不是任何数据都能发送的，现在只能发送三类数据，包括UTF-8的string类型（会默认转化为USVString），ArrayBuffer和Blob，且只有在建立连接后才能使用。（感谢大佬指出错误，已修改）</li>
<li>在使用socket.close(code,[reason])关闭连接时，code和reason都是选填的。code是一个数字值表示关闭连接的状态号，表示连接被关闭的原因。如果这个参数没有被指定，默认的取值是1000 （表示正常连接关闭）,而reason是一个可读的字符串，表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本。</li>
</ul>
<h3 id="1-ws和wss"><a href="#1-ws和wss" class="headerlink" title="1.ws和wss"></a>1.ws和wss</h3><p>我们在上面提到过，创建一个 socket 实例时可以选填ws和wss来进行通信协议的确定。他们两个其实很像HTTP和HTTPS之间的关系。其中ws表示纯文本通信，而wss表示使用加密信道通信（TCP+TLS）。那为啥不直接使用HTTP而要自定义通信协议呢？这就要从WebSocket的目的说起来，WebSocket 的主要功能就是为了给浏览器中的应用与服务器端提供优化的，双向的通信机制，但这不代表 WebScoket 只能局限于此，它当然还能够用于其他的场景，这就需要他可以通过非HTTP协议来进行数据交换，因此 WebSocket 也就采用了自定义 URI 模式，以确保就算没有HTTP，也能进行数据交换。</p>
<p>ws和wss：</p>
<ul>
<li><strong>ws协议</strong>：普通请求，占用与HTTP相同的80端口</li>
<li><strong>wss协议</strong>：基于SSL的安全传输，占用与TLS相同的443端口。</li>
</ul>
<p>注：有些HTTP中间设备有时候可能会不理解WebSocket，而导致各种诸如：盲目连接升级，乱修改内容等问题。而WSS就很好的解决了这个问题，它建立了一个端到端的安全通道，这个通道对中间设备模糊了数据，因此中间设备就不能感知到数据，也就无法对请求做一些特殊处理了。</p>
<h2 id="三、WebSocket协议的规范"><a href="#三、WebSocket协议的规范" class="headerlink" title="三、WebSocket协议的规范"></a>三、WebSocket协议的规范</h2><p>以下是一个典型的WebSocket发起请求到响应请求的示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">客户端到服务端：</span><br><span class="line">GET / HTTP/1.1</span><br><span class="line">Connection:Upgrade</span><br><span class="line">Host:127.0.0.1:8088</span><br><span class="line">Origin:null</span><br><span class="line">Sec-WebSocket-Extensions:x-webkit-deflate-frame</span><br><span class="line">Sec-WebSocket-Key:puVOuWb7rel6z2AVZBKnfw==</span><br><span class="line">Sec-WebSocket-Version:13</span><br><span class="line">Upgrade:websocket</span><br><span class="line"></span><br><span class="line">服务端到客户端：</span><br><span class="line">HTTP/1.1 101 Switching Protocols</span><br><span class="line">Connection:Upgrade</span><br><span class="line">Server:beetle websocket server</span><br><span class="line">Upgrade:WebSocket</span><br><span class="line">date: Thu, 10 May 2018 07:32:25 GMT</span><br><span class="line">Access-Control-Allow-Credentials:true</span><br><span class="line">Access-Control-Allow-Headers:content-type</span><br><span class="line">Sec-WebSocket-Accept:FCKgUr8c7OsDsLFeJTWrJw6WO8Q=</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到，WebSocket协议和HTTP协议乍看并没有太大的区别，但细看下来，区别还是有些的，这其实是一个握手的http请求，首先请求和响应的，”Upgrade:WebSocket”表示请求的目的就是要将客户端和服务器端的通讯协议从 HTTP 协议升级到 WebSocket协议。从客户端到服务器端请求的信息里包含有”Sec-WebSocket-Extensions”、“Sec-WebSocket-Key”这样的头信息。这是客户端浏览器需要向服务器端提供的握手信息，服务器端解析这些头信息，并在握手的过程中依据这些信息生成一个28位的安全密钥并返回给客户端，以表明服务器端获取了客户端的请求，同意创建 WebSocket 连接。</p>
<p>当握手成功后，这个时候TCP连接就已经建立了，客户端与服务端就能够直接通过WebSocket直接进行数据传递。不过服务端还需要判断一次数据请求是什么时候开始的和什么时候是请求的结束的。在WebSocket中，由于浏览端和服务端已经打好招呼，如我发送的内容为utf-8 编码，如果我发送0x00,表示包的开始，如果发送了0xFF，就表示包的结束了。这就解决了黏包的问题。</p>
<h2 id="四、兼容性情况"><a href="#四、兼容性情况" class="headerlink" title="四、兼容性情况"></a>四、兼容性情况</h2><pre><code>浏览器                     支持情况
Chrome                Supported in version 4+
Firefox                Supported in version 4+
Internet Explorer    Supported in version 10+
Opera                Supported in version 10+
Safari                Supported in version 5+
</code></pre><h2 id="五、Socket-IO"><a href="#五、Socket-IO" class="headerlink" title="五、Socket.IO"></a>五、Socket.IO</h2><p>简单来说Socket.IO就是对WebSocket的封装，并且实现了WebSocket的服务端代码。Socket.IO将WebSocket和轮询（Polling）机制以及其它的实时通信方式封装成了通用的接口，并且在服务端实现了这些实时机制的相应代码。也就是说，WebSocket仅仅是Socket.IO实现实时通信的一个子集。Socket.IO简化了WebSocket API，统一了返回传输的API。传输种类包括：</p>
<ul>
<li>WebSocket</li>
<li>Flash Socket</li>
<li>AJAX long-polling</li>
<li>AJAX multipart streaming</li>
<li>IFrame</li>
<li>JSONP polling。</li>
</ul>
<p>上面的排序基本上是根据传输的速度进行排序的，socket.io会根据浏览器的兼容情况对这些传输种类进行选择。</p>
<p>我们来看一下服务端的Socket.IO基本API：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入socke.io</span></span><br><span class="line"><span class="keyword">const</span> io = <span class="built_in">require</span>(<span class="string">'socket.io'</span>)(<span class="number">80</span>)</span><br><span class="line"><span class="comment">// 监听客户端连接,回调函数会传递本次连接的socket</span></span><br><span class="line">io.on(<span class="string">'connection'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">socket</span>))</span></span><br><span class="line"><span class="function">// 给所有客户端广播消息</span></span><br><span class="line"><span class="function"><span class="title">io</span>.<span class="title">sockets</span>.<span class="title">emit</span>(<span class="params"><span class="string">'String'</span>,data</span>)</span></span><br><span class="line"><span class="function">// 给指定的客户端发送消息</span></span><br><span class="line"><span class="function"><span class="title">io</span>.<span class="title">sockets</span>.<span class="title">socket</span>(<span class="params">socketid</span>).<span class="title">emit</span>(<span class="params"><span class="string">'String'</span>, data</span>)</span></span><br><span class="line"><span class="function">// 监听客户端发送的信息</span></span><br><span class="line"><span class="function"><span class="title">socket</span>.<span class="title">on</span>(<span class="params"><span class="string">'String'</span>,function(data</span>))</span></span><br><span class="line"><span class="function">// 给该<span class="title">socket</span>的客户端发送消息</span></span><br><span class="line"><span class="function"><span class="title">socket</span>.<span class="title">emit</span>(<span class="params"><span class="string">'String'</span>, data</span>)</span></span><br></pre></td></tr></table></figure></p>
<p>另外，Socket.IO还提供了一个Node.JS API，它看起来很像客户端API。所以我们来看看它的实际应用吧：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// socket-server.js</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 需要使用HTTP模块来启动服务器和Socket.IO</span></span><br><span class="line"><span class="keyword">const</span> http= <span class="built_in">require</span>(<span class="string">'http'</span>), </span><br><span class="line"><span class="keyword">const</span> io= <span class="built_in">require</span>(<span class="string">'socket.io'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> server= http.createServer(<span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>)</span>&#123; </span><br><span class="line">    <span class="comment">// 发送HTML的headers和message</span></span><br><span class="line">    res.writeHead(<span class="number">200</span>,&#123; <span class="string">'Content-Type'</span>: <span class="string">'text/html'</span> &#125;)</span><br><span class="line">    res.end(<span class="string">'&lt;p&gt;Hello Socket.IO!&lt;p&gt;'</span>)</span><br><span class="line">&#125;); </span><br><span class="line"><span class="comment">// 在8080端口启动服务器</span></span><br><span class="line">server.listen(<span class="number">8080</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建一个Socket.IO实例，并把它传递给服务器</span></span><br><span class="line"><span class="keyword">const</span> socket= io.listen(server)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加一个连接监听器</span></span><br><span class="line">socket.on(<span class="string">'connection'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">client</span>) </span>&#123; </span><br><span class="line"></span><br><span class="line"><span class="comment">// 连接成功，开始监听</span></span><br><span class="line">client.on(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Received message from client!'</span>,event)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 连接失败</span></span><br><span class="line">client.on(<span class="string">'disconnect'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </span><br><span class="line">    clearInterval(interval)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Server has disconnected'</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>然后我们就可以启动这个文件了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node socket-server.js</span><br></pre></td></tr></table></figure>
<p>然后我们就可以创建一个每秒钟发送消息到客户端的发送器了；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> interval= setInterval(<span class="function"><span class="params">()</span> =&gt;</span> &#123; </span><br><span class="line">  client.send(<span class="string">'This is a message from the server,hello world'</span> + <span class="keyword">new</span> <span class="built_in">Date</span>().getTime())</span><br><span class="line">&#125;,<span class="number">1000</span>)</span><br></pre></td></tr></table></figure>
<hr>
<p>注：需要注意的是，如果我们想在前端使用socket.IO,我们需要下载这个：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install socket.io-client --save</span><br></pre></td></tr></table></figure>
<p>然后再连接网络：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> io <span class="keyword">from</span> <span class="string">'socket.io-client'</span></span><br><span class="line"><span class="keyword">const</span> socket = io(<span class="string">'ws://localhost:8080'</span>)</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/计算机网络/" rel="tag"># 计算机网络</a>
          
            <a href="/blog/tags/HTML5/" rel="tag"># HTML5</a>
          
            <a href="/blog/tags/WebSocket/" rel="tag"># WebSocket</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/聊一聊常见的浏览器端数据存储方案/" rel="next" title="聊一聊常见的浏览器端数据存储方案">
                <i class="fa fa-chevron-left"></i> 聊一聊常见的浏览器端数据存储方案
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/15/那些前端应该知道的HTTP知识/" rel="prev" title="那些前端应该知道的HTTP知识">
                那些前端应该知道的HTTP知识 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#HTML5-WebSocket概述"><span class="nav-number">1.</span> <span class="nav-text">HTML5 WebSocket概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一、WebSocket产生的背景"><span class="nav-number">2.</span> <span class="nav-text">一、WebSocket产生的背景</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-黎明前的黑暗——实时web应用的需求"><span class="nav-number">2.1.</span> <span class="nav-text">1.黎明前的黑暗——实时web应用的需求</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-长轮询机制"><span class="nav-number">2.1.1.</span> <span class="nav-text">1.1 长轮询机制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-流技术机制"><span class="nav-number">2.1.2.</span> <span class="nav-text">1.2 流技术机制</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-黎明的到来——WebSocket"><span class="nav-number">2.2.</span> <span class="nav-text">2.黎明的到来——WebSocket</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、WebSocket-API的用法"><span class="nav-number">3.</span> <span class="nav-text">二、WebSocket API的用法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-ws和wss"><span class="nav-number">3.1.</span> <span class="nav-text">1.ws和wss</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、WebSocket协议的规范"><span class="nav-number">4.</span> <span class="nav-text">三、WebSocket协议的规范</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、兼容性情况"><span class="nav-number">5.</span> <span class="nav-text">四、兼容性情况</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、Socket-IO"><span class="nav-number">6.</span> <span class="nav-text">五、Socket.IO</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
